package no.group.gowther.util;

import no.group.gowther.exception.UncompressFailureException;
import org.springframework.lang.NonNull;

import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ayatsuji
 * @date 2022-04-19 23:02
 * @since
 */
public class UncompressFileUtils {
    public static boolean uncompress(Path filePath, Path targetDirPath, @NonNull String pwd) throws UncompressFailureException {
            try {
                int state = startProcess(buildUncompressCommand(filePath, targetDirPath, pwd));
                return state == 0;
            } catch (IOException | InterruptedException e) {
                throw new UncompressFailureException(String.format("解压文件[%s]到[%s]失败", filePath, targetDirPath), e);
            }
    }

    public static void uncompress(Path filePath, Path targetDirPath, @NonNull List<String> pwdList) throws UncompressFailureException {
        if (pwdList.isEmpty()) pwdList.add("");
        for (String pwd: pwdList) {
            try {
                int state = startProcess(buildUncompressCommand(filePath, targetDirPath, pwd));
                if (state == 0) {
                    return;
                }
            } catch (IOException | InterruptedException e) {
                throw new UncompressFailureException(String.format("解压文件[%s]到[%s]失败", filePath, targetDirPath), e);
            }
        }
        throw new UncompressFailureException(String.format("解压文件[%s]到[%s]失败，密码错误", filePath, targetDirPath));
    }

    private static int startProcess(List<String> command) throws IOException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(true);
        Process process = pb.start();
        return process.waitFor();
    }

    private static List<String> buildUncompressCommand(Path filePath, Path targetDirPath, String pwd) {
        List<String> command = new ArrayList<>(6);
        command.add("7z");
        command.add("x");
        command.add(filePath.toString());
        command.add("-o" + targetDirPath.toString());
        command.add("-y");
        command.add("-p" + pwd);
        return command;
    }
}
